import { Modal, Steps, Form, Input, Row, Col, message } from 'antd';
import React, { useState, useCallback } from 'react';
import { useRequest } from '@umijs/hooks';
import PhoneValidate from '@/components/blocks/PhoneValidate';
import PasswordValidate from '@/components/blocks/PasswordValidate';
import { forgetPassword } from '../service';
import { aesEncrypt } from '@/config/cryptoService';

const ForgetPasswd = function ForgetPasswd(props) {
  const { visible, onClose } = props;
  const { getFieldDecorator, validateFields } = props.form;
  const [step, setStep] = useState(0);
  const [findBackWay, setFindBackWay] = useState(1);
  const [preParams, setPreParams] = useState({});

  const { loading, run } = useRequest(
    values => {
      let aesEncryptValue = JSON.parse(JSON.stringify(values));
      aesEncryptValue.password && (aesEncryptValue.password = aesEncrypt(aesEncryptValue.password));
      aesEncryptValue.checkPassword && (aesEncryptValue.checkPassword = aesEncrypt(aesEncryptValue.checkPassword));
      return forgetPassword({ ...preParams, ...aesEncryptValue, type: findBackWay })
    },
    {
      manual: true,
      onSuccess(data, [param]) {
        setPreParams({ ...preParams, ...param });
        if (step === 2) {
          onClose();
          message.success('密码修改成功');
        }
        setStep(pre => pre + 1);
      },
      onError(res, re) {
        console.log(res, re);
      },
    },
  );

  const onOk = useCallback(() => {
    if (step === 0) {
      validateFields(['userName']).then(run);
    } else if (step === 1) {
      validateFields(['userName', 'phoneNum', 'smsCode']).then(run);
    } else if (step === 2) {
      validateFields(['userName', 'phoneNum', 'smsCode', 'password', 'checkPassword']).then(run);
    }
  }, [step, validateFields, run]);

  const getCode = useCallback(() => {
    return new Promise((resolve, rej) => {
      validateFields(['userName', 'phoneNum']).then(param => {
        return forgetPassword({ ...preParams, ...param, type: findBackWay })
          .then(res => {
            setPreParams({ ...preParams, ...param });
            return res;
          })
          .then(resolve)
          .catch(rej);
      });
    });
  }, [validateFields, findBackWay, preParams]);

  const onChangeStep = useCallback(
    current => {
      if (step > current) {
        setStep(current);
      }
    },
    [step],
  );

  const formLayout = {
    labelCol: { span: 9 },
    wrapperCol: { span: 15 },
  };

  return (
    <Modal
      visible={visible}
      onCancel={onClose}
      onOk={onOk}
      okButtonProps={{ loading }}
      okText="下一步"
      title="找回密码"
      width="72%"
      bodyStyle={{ minHeight: '50vh', display: 'flex', flexDirection: 'column' }}
    >
      <Steps
        labelPlacement="vertical"
        current={step}
        onChange={onChangeStep}
        style={{ marginBottom: 24 }}
      >
        <Steps.Step title="输入账号信息" />
        <Steps.Step title="选择找回方式" />
        <Steps.Step title="重置密码" />
      </Steps>
      <Row justify="center" type="flex" align="middle" style={{ flex: 1 }}>
        <Col>
          <Form>
            {step === 0 && (
              <Form.Item {...formLayout} label="找回账号">
                {getFieldDecorator('userName', {
                  initialValue: '',
                  rules: [{ required: true, message: '请输入系统账号' }],
                })(<Input size="large" placeholder="请输入系统账号" allowClear />)}
              </Form.Item>
            )}
            {step === 1 && (
              <>
                {/* <Radio.Group onChange={e => setFindBackWay(e.target.value)} value={findBackWay} style={{marginBottom: 24}}>
                <Radio value={1}>短信找回</Radio>
                <Radio value={2}>邮件解锁</Radio>
                <Radio value={3}>人工解锁</Radio>
              </Radio.Group> */}
                {findBackWay === 1 ? (
                  <PhoneValidate {...props} formLayout={formLayout} onGetCode={getCode} />
                ) : (
                    <Form.Item {...formLayout} label="找回账号">
                      {getFieldDecorator('userName', {
                        rules: [{ required: true, message: '请输入系统账号' }],
                      })(<Input size="large" placeholder="请输入系统账号" allowClear />)}
                    </Form.Item>
                  )}
              </>
            )}
            {step === 2 && <PasswordValidate {...props} formLayout={formLayout} />}
          </Form>
        </Col>
      </Row>
    </Modal>
  );
};

export default Form.create()(ForgetPasswd);
